package base.core.log;

import com.fasterxml.jackson.core.JsonProcessingException;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

import lombok.extern.slf4j.Slf4j;

/**
 * 打印系统日志
 */
@Slf4j(topic = "com.elegant.log.sql.spend")
@Aspect
@Component
@ConditionalOnProperty(name = "logging.sql-spend",havingValue = "true")
public class LogSqlSpendTime {
   private final static ThreadLocal<LocalDateTime> sqlBeginTime = new ThreadLocal();
    /**
     * 打印接口日志
     */
    @Pointcut(value = "execution(* base.core.spring.BaseMapper.*(..))||execution(* com.baomidou.mybatisplus.core.mapper.BaseMapper.*(..))")
    public void api() {
    }

    @Before(value = "api()")
    public void beforeApi() {
        sqlBeginTime.set(LocalDateTime.now());
    }

    @After(value = "api()")
    public void afterApi(JoinPoint joinPoint) throws JsonProcessingException {
        log.debug("<=> SQL执行时间: {} ms", ChronoUnit.MILLIS.between(sqlBeginTime.get(),LocalDateTime.now()));
    }

}